﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Diagnostics;
using Microsoft.Win32;

namespace JaikuClient
{
    public partial class mainForm : Form
    {
        public Boolean didUseSaveInfo;
        public Boolean didRecentClear;
        public String proxyPassword;
        public String proxyUser;
        public String UseProxyStr;
        public String UseProxyAuthStr;
        public String proxyAddress;
        public String proxyPort;

        public mainForm()
        {
            InitializeComponent();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("http://api.jaiku.com/key");
        }

        private void updateCharCount(object sender, KeyPressEventArgs e)
        {
            Int32 CharCount = 0;
            Int32 Remaining = 0;
            CharCount = presence_txtbox.Text.Length;
            Remaining = 139 - CharCount + 1;
            remaining_label.Text = Remaining.ToString();
            if (didRecentClear)
            {
                CharCount = presence_txtbox.Text.Length;
                Remaining = 139 - CharCount + 1;
                remaining_label.Text = Remaining.ToString();
                didRecentClear = false;
            }

        }

        private void updateCharCount(object sender, EventArgs e)
        {
            Int32 CharCount = 0;
            Int32 Remaining = 0;
            CharCount = presence_txtbox.Text.Length;
            Remaining = 139 - CharCount + 1;
            remaining_label.Text = Remaining.ToString();
            if (didRecentClear)
            {
                CharCount = presence_txtbox.Text.Length;
                Remaining = 139 - CharCount + 1;
                remaining_label.Text = Remaining.ToString();
                didRecentClear = false;
            }


        }

        private void clearContents(object sender, EventArgs e)
        {
            presence_txtbox.Text = "";
            remaining_label.Text = "140";
            didRecentClear = true;
        }

        private void doUpdatePresence(object sender, EventArgs e)
        {
            try
            {

                String username = username_txtbox.Text.ToString();
                String apikey = apikey_txtbox.Text.ToString();
                String presence = presence_txtbox.Text.ToString();
                String apiurl = "http://api.jaiku.com/json";
                
                HttpWebRequest HttpRequest = (HttpWebRequest)WebRequest.Create(apiurl);
                if (UseProxyStr == "1")
                {
                    HttpRequest.Proxy = new WebProxy(String.Format("{0}:{1}", proxyAddress, proxyPort));
                    if (UseProxyAuthStr == "1")
                    {
                        HttpRequest.Proxy.Credentials = new NetworkCredential(proxyUser, proxyPassword);
                    }
                }
                String postData = "user=" + username + "&personal_key=" + apikey + "&method=presence.send&message=" + presence;
                HttpRequest.UserAgent = "jaiku-client/s0rs.net v0.1";
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(postData);

                HttpRequest.Method = "POST";
                HttpRequest.ContentType = "application/x-www-form-urlencoded";
                HttpRequest.ContentLength = data.Length;
                System.IO.Stream apiStream = HttpRequest.GetRequestStream();
                apiStream.Write(data, 0, data.Length);
                WebResponse response = HttpRequest.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream());
                String apiResponse = sr.ReadToEnd().Trim().ToString();
                if (apiResponse.Contains("\"status\": \"ok\""))
                {
                    presence_txtbox.Text = "";
                    remaining_label.Text = "140";
                    MessageBox.Show("Your presence has been updated!", "Presence updated");
                    didRecentClear = true;
                }
                else
                {
                    MessageBox.Show(String.Format("An error encountered while updating presence, please check your username and API key!\napi response:\n{0}", apiResponse), "Error while updating presence");
                }
                apiStream.Close();

            }
            catch (Exception errormsg)
            {
                MessageBox.Show(String.Format("An unspecified error was encountered while updating presence\ndetails:\n{0}", errormsg), "Error while updating presence");
            }
        }

        private void showAboutBox(object sender, EventArgs e)
        {
            Form aboutBox = new AboutBox();
            aboutBox.Show();
        }

        private void handleResize(object sender, EventArgs e)
        {
            notifyIcon1.BalloonTipTitle = "Jaiku Client";
            notifyIcon1.BalloonTipText = "Jaiku Client will continue to run in background, to update your presence double click this icon.";

            if (this.WindowState == FormWindowState.Minimized)
            {
                notifyIcon1.Visible = true;
                notifyIcon1.ShowBalloonTip(1000);
                this.Hide();
            }
            else if (this.WindowState == FormWindowState.Normal)
            {
                notifyIcon1.Visible = false;
            }

        }

        private void handleRestore(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void handleFocus(object sender, EventArgs e)
        {

            Int32 CharCount = 0;
            Int32 Remaining = 0;
            CharCount = presence_txtbox.Text.Length;
            Remaining = 139 - CharCount + 1;
            remaining_label.Text = Remaining.ToString();
            if (didRecentClear)
            {
                CharCount = presence_txtbox.Text.Length;
                Remaining = 139 - CharCount + 1;
                remaining_label.Text = Remaining.ToString();
                didRecentClear = false;
            }
            try
            {
                String username;
                String apikey;
                RegistryKey rk = Registry.CurrentUser;
                RegistryKey myrk = rk.OpenSubKey("SOFTWARE\\s0rs networks\\Jaiku Client");
                username = (string)myrk.GetValue("USERNAME");
                apikey = (string)myrk.GetValue("APIKEY");
                if (username_txtbox.Text == "" && apikey_txtbox.Text == "" && username != "" && apikey != "")
                {
                    username_txtbox.Text = username;
                    apikey_txtbox.Text = apikey;

                    didUseSaveInfo = true;
                    linkLabel2.Text = "clear my info";
                }
                if(username == "" || apikey == "")
                {
                    linkLabel2.Text = "save my info";
                }
            }
            catch (Exception error)
            { didUseSaveInfo = false; }
        }
        private void LoadNetworkSettings()
        {


            RegistryKey rk = Registry.CurrentUser;
            RegistryKey myrk = rk.CreateSubKey("SOFTWARE\\s0rs networks\\Jaiku Client\\HTTP Proxy");
            UseProxyStr = (string)myrk.GetValue("USE_PROXY");
            UseProxyAuthStr = (string)myrk.GetValue("USE_PROXY_AUTH");
            proxyAddress = (string)myrk.GetValue("PROXY_ADDRESS");
            proxyPort = (string)myrk.GetValue("PROXY_PORT");
            proxyUser = (string)myrk.GetValue("PROXY_USER");
            proxyPassword = (string)myrk.GetValue("PROXY_PASSWORD");
           
        }

        private void saveInfoToRegistry(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (didUseSaveInfo)
            {
                //Used saved info, so clear the saved info!
                try
                {
                    RegistryKey rk = Registry.CurrentUser;
                    RegistryKey myrk = rk.CreateSubKey("SOFTWARE\\s0rs networks\\Jaiku Client");
                    myrk.DeleteValue("USERNAME");
                    myrk.DeleteValue("APIKEY");
                    username_txtbox.Text = "";
                    apikey_txtbox.Text = "";
                    linkLabel2.Text = "save my info";
                    didUseSaveInfo = false;
                }
                catch (Exception errormsg)
                {
                    didUseSaveInfo = false;
                    username_txtbox.Text = "";
                    apikey_txtbox.Text = "";
                    linkLabel2.Text = "save my info";
                }

            }
            else
            {

                try
                {
                    String username = username_txtbox.Text.ToString();
                    String apikey = apikey_txtbox.Text.ToString();
                    RegistryKey rk = Registry.CurrentUser;
                    RegistryKey myrk = rk.CreateSubKey("SOFTWARE\\s0rs networks\\Jaiku Client");
                    myrk.SetValue("USERNAME", username);
                    myrk.SetValue("APIKEY", apikey);
                    linkLabel2.Text = "clear my info";
                    didUseSaveInfo = true;
                }
                catch (Exception error)
                {
                    didUseSaveInfo = true;
                    linkLabel2.Text = "clear my info";


                }
            }
        }

        private void showNetworkSettings(object sender, EventArgs e)
        {
            NetworkSettingsForm netSettings = new NetworkSettingsForm();
            netSettings.Show();
        }

        private void LoadSettings(object sender, EventArgs e)
        {
            LoadNetworkSettings();
        }
    }
}
